﻿//We are given integer number n, value v (v=0 or 1) and a position p. 
//Write a sequence of operators that modifies n to hold the value v at the position p from the binary representation of n.
//Example: n = 5 (00000101), p=3, v=1 -> 13 (00001101)
//         n = 5 (00000101), p=2, v=0 -> 1 (00000001)

using System;

class SetBitAtPosition
{
    static void Main()
    {
        Console.Write("Enter integer number: ");
        int integerNumber = int.Parse(Console.ReadLine());
        Console.Write("Enter position: ");
        int position = int.Parse(Console.ReadLine());
        Console.Write("Enter bit value (0 or 1): ");
        byte bitNewValue = byte.Parse(Console.ReadLine());

        if (bitNewValue == 1 || bitNewValue == 0)
        {
            int newNumber;
            if (bitNewValue == 1)
                newNumber = TurnBitPositionOn(integerNumber, position);
            else
                newNumber = TurnBitPositionOff(integerNumber, position);
            Console.WriteLine("n = {0} ({1}), p = {2}, v = {3} -> {4} ({5})", integerNumber, Convert.ToString(integerNumber, 2).PadLeft(8, '0'), position, bitNewValue, newNumber, Convert.ToString(newNumber, 2).PadLeft(8, '0'));
        }
        else
            Console.WriteLine("Wrong bit value. The number must be 0 or 1");
    }

    private static int TurnBitPositionOn(int number, int bitPosition)
    {
        int mask = 1 << bitPosition;
        return (number | mask);
    }

    private static int TurnBitPositionOff(int number, int bitPosition)
    {
        int mask = ~(1 << bitPosition);
        return (number & mask);
    }
}
